﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ListForms;

namespace ListsForm.Product
{
    public partial class FrmEditProduct : FrmBaseEditForm
    {
        public FrmEditProduct(Lists.Product product)
        {
            InitializeComponent();           
            if (product == null)
            {
                _EditState = EditState.CreatingNew;
                bindingSource.AddNew();
                this.Text = "New Product";
            }
            else
            {
                _EditState = EditState.Modifying;
                bindingSource.Add(DB.Products.FirstOrDefault(p => p.ProductID == product.ProductID));
                this.Text = "Edit Product";
            }
        }

        protected override void CheckFullInfo()
        {
            Lists.Product product = (Lists.Product)bindingSource.Current;
            if (product.ProductID == null)
                throw new Exception("ProductID not allow null");
            if (string.IsNullOrEmpty(product.ProductName))
                throw new Exception("Product Name not allow null");
            if (string.IsNullOrEmpty(product.Unit))
                throw new Exception("Unit not allow null");
            if (product.DeliveringPrice == null)
                throw new Exception("Delivering price not allow null");
            if (product.ReceivingPrice == null)
                throw new Exception("Receiving price not allow null");
            if (Convert.ToDecimal(product.DeliveringPrice)<=Convert.ToDecimal(product.ReceivingPrice))
            {
                throw new Exception("Don't delivering price smaller than receiving price");
            }
        }

        protected override void SaveAndClose()
        {
            Lists.Product product = (Lists.Product)bindingSource.Current;
            if (_EditState == EditState.CreatingNew)
            {
                product.InStockQuantity = 0;
                product.ReceivedDate = DateTime.Now;
                DB.Products.InsertOnSubmit(product);
            }
            DB.SubmitChanges();
            this.Close();
        }
    }
}
